package com.yazi.mxz.server.controller;

import java.util.List;

import javax.annotation.Resource;
import com.fasterxml.jackson.annotation.JsonView;
import com.yazi.mxz.common.config.MyUtil;
import com.yazi.mxz.common.entity.beans.Member;
import com.yazi.mxz.common.service.MemberService;
import com.yazi.mxz.server.request.UpdatePwdDoRequest;
import com.yazi.mxz.server.response.MemberResponse;
import com.yazi.mxz.server.response.RegisterResponse;
import com.yazi.mxz.server.response.StatusResponse;
import com.yazi.mxz.server.response.view.BaseView;

import mo.framework.smh.hibernate.PageInfo;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller("memberController")
@RequestMapping("/member")
public class MemberController extends BaseController {
	private static Logger log = LoggerFactory.getLogger(MemberController.class);
	@Resource
	MemberService memberService;
	
	/**
	 * 检查注册用户名的唯一性
	 * @param comReq
	 * @return
	 */
	@RequestMapping("/checkName")
	@ResponseBody
	public StatusResponse checkRegisterName(@RequestBody Member member) {
		log.debug("客户端请求 -> 检查用户名唯一性");
		List<Member> list = memberService.search(member, new PageInfo(), null);
		StatusResponse res = new StatusResponse();
		if (list.size() > 0) {
			res.setFailMessage("用户名已经存在");
		} else {
			res.setOkMessage("ok");
		}
		return res;
	}
	
	@RequestMapping("/registerDo")
	@ResponseBody
	@JsonView(BaseView.class)
	public RegisterResponse registerDo(@RequestBody Member member) {
		log.debug("客户端请求 -> 注册用户");
		RegisterResponse res = new RegisterResponse();
		
		//...TODO 在这里进行用户填写内容验证
		/*
		List<String> fields = new ArrayList<String>();
		fields.add("name");// 记录验证未能通过的字段属性
		fields.add("password");
		fields.add("storeId");
		fields.add("regionId");
		res.setFailData(fields);
		*/
		try {
			member = memberService.add(member);
			member.setSeed(null);
			member.setPassword(null);// 禁止返回密码
			res.setSuccessData(member);
			res.setOkMessage("注册成功");
		} catch(Exception e) {
			log.error("注册异常:", e);
			res.setErrorMessage("注册失败,请联系管理员");
		}
		return res;
	}
	
	@RequestMapping("/loginDo")
	@ResponseBody
	@JsonView(BaseView.class)
	public MemberResponse loginDo(@RequestBody Member member) {
		log.debug("客户端请求 -> 用户登录");
		MemberResponse res = new MemberResponse();
		try {
			
			UsernamePasswordToken token = new UsernamePasswordToken();
			token.setUsername(member.getName());
			token.setPassword(member.getPassword().toCharArray());
			token.setRememberMe(true);
			Subject subject = SecurityUtils.getSubject();
			subject.login(token);
			
			member = getLoginMember();
			member.setSeed(null);
			member.setPassword(null);// 禁止返回密码
			res.setSuccessData(member);
			res.setOkMessage("登录成功");
			
		} catch (AuthenticationException e) {
			res.setFailMessage("用户名或者密码错误");
		} catch(Exception e) {
			log.error("登录异常:", e);
			res.setErrorMessage("操作失败,请联系管理员");
		}
		return res;
	}
	
	/**
	 * 修改密码
	 * @param req
	 * @return
	 */
	@RequestMapping("/editPwdDo")
	@ResponseBody
	public StatusResponse editPwdDo(@RequestBody UpdatePwdDoRequest req) {
		Member loginMember = getLoginMember();
		log.debug("客户端请求 -> 修改密码：memberId={}", loginMember.getMemberId());
		StatusResponse res = new StatusResponse();
		try {
			// 检查旧密码
			int seed = loginMember.getSeed();
			String oldPwd = MyUtil.encodePwd(req.getOldPwd() + seed);
			if (!oldPwd.equals(loginMember.getPassword())) {
				res.setFailMessage("旧密码不正确");
				return res;
			}
			
			Member member = new Member();
			member.setPassword(req.getNewPwd());
			memberService.update(loginMember, member);
			res.setOkMessage("修改成功");
		} catch (Exception e) {
			log.error("修改密码异常:", e);
			res.setErrorMessage("操作失败,请联系管理员");
		}
		
		return res;
	}
	
}
